<?php
/*
 *  Update arrears
 *  One new record reflecting several stats is created every day for each delinquent loan.
 *  Depending on the delinquent portfolio size, this update could take quite some time,
 *  be sure to adjust the php run overtime accordingly.
 */
require_once 'z.php';
require_once APPLICATION_PATH . '/modules/loan/models/Loans.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanStatusChanges.php';
require_once APPLICATION_PATH . '/modules/loan/models/Payments.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanWriteOffCharges.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanWriteOffPayments.php';

$activeLoans = new Zend_Db_Table(array('name' => 'active_loans', 'primary' => 'LoanId'));
$arrears = new Zend_Db_Table(array('name' => 'arrears', 'primary' => 'ArrearId'));

$db = Zend_Db_Table_Abstract::getDefaultAdapter();

$dloans = $activeLoans->fetchAll($activeLoans->select()->where('CurrentDelay > 0')); //->limit(10)

$date = date('Y-m-d');
$db->beginTransaction();
try {
    foreach ($dloans as $row) {
        $plan = new Emms_PmtPlan(new Emms_Loan($row->LoanId));
        $payment = 0;
        $penalty = 0;
        $interest = 0;
        $loanInsurance = 0;
        $healthInsurance = 0;
        $administrativeFee = 0;
        $principal = 0;
        $totalDelay = 0;
        $hits = 0;
        foreach($plan->getSchPmtObj() as $schPayment) {
            if($schPayment->Paid) continue;
            if($schPayment->Date > $date) break;
            $payment                 += $schPayment->Pmt;
            $penalty                 += $schPayment->Penalties;
            $interest                += $schPayment->Interest;
            $loanInsurance           += $schPayment->LoanInsurance;
            $healthInsurance         += $schPayment->HealthInsurance;
            $administrativeFee       += $schPayment->AdministrativeFee;
            $principal               += $schPayment->Principal;
            $totalDelay              += $schPayment->Delay;
           $hits++;
        }
        
        $arrears->insert(array(
            'LoanId' => $row->LoanId,
            'Date' => $date,
            'BalancePrincipal' => $row->BalancePrincipal,
            'BalanceLoanInsurance' => $row->BalanceLoanInsurance,
            'BalanceHealthInsurance' => $row->BalanceHealthInsurance,
            'BalanceAdministrativeFee' => $row->BalanceAdministrativeFee,
            'Payment' => $payment,
            'Penalty' => $penalty,
            'Interest' => $interest,
            'LoanInsurance' => $loanInsurance,
            'HealthInsurance' => $healthInsurance,
            'AdministrativeFee' => $administrativeFee,
            'Principal' => $principal,
            'Hits' => $hits,
            'Delay' => $row->CurrentDelay,
            'TotalDelay' => $totalDelay
        ));
    }
} catch  (Zend_Exception $e) {
    $db->rollBack();
    echo $e->getMessage();
    exit;
}
$db->commit();

?>
